package com.example.clock_demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.clock_demo.common.Result;
import com.example.clock_demo.dto.AttendanceDailyRecordDTO;
import com.example.clock_demo.dto.AttendanceMonthlyReportDTO;
import com.example.clock_demo.dto.MonthlyAttendanceSummaryByTeamDTO;
import com.example.clock_demo.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.YearMonth;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/attendance")
@Api(tags = "考勤管理")
public class AttendanceController {

    @Autowired
    private AttendanceService attendanceService;


    /**
     * 获取指定查询条件和月份的月度考勤报告，支持分页。
     * GET /attendance/report/monthly?yearMonth=2025-07&teamName=生产&employeeName=张&pageNum=1&pageSize=10
     *
     * @param yearMonth 月份 (格式: yyyy-MM)
     * @param teamName 班组名称 (模糊查询，可选)
     * @param employeeName 姓名 (模糊查询，可选)
     * @param pageNum 当前页码 (从1开始)
     * @param pageSize 每页记录数
     * @return 分页的月度考勤报告列表
     */
    @GetMapping("/report/monthly")
    @ApiOperation("获取月度考勤报告")
    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    public Result<Page<AttendanceMonthlyReportDTO>> getMonthlyAttendanceReports(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM") YearMonth yearMonth, // 变更：使用 YearMonth 类型和注解
            @RequestParam(required = false) String teamName,
            @RequestParam(required = false) String employeeName,
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize) {

        try {
            Page<AttendanceMonthlyReportDTO> result = attendanceService.getMonthlyAttendanceReports(
                    yearMonth, teamName, employeeName, pageNum, pageSize); // 变更：传入 YearMonth
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取月度考勤报告失败: " + e.getMessage());
        }
    }

    /**
     * 查询任意人员在指定时间段内的日考勤记录，支持分页。
     * GET /attendance/daily/search?startDate=2025-07-01&endDate=2025-07-31&teamName=生产&employeeName=张&pageNum=1&pageSize=10
     *
     * @param startDate 查询开始日期 (格式: yyyy-MM-dd)
     * @param endDate 查询结束日期 (格式: yyyy-MM-dd)
     * @param teamName 班组名称 (模糊查询，可选)
     * @param employeeName 姓名 (模糊查询，可选)
     * @param pageNum 当前页码 (从1开始)
     * @param pageSize 每页记录数
     * @return 分页的日考勤记录列表
     */
    @GetMapping("/daily/search")
    @ApiOperation("查询日考勤记录")
    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    public Result<Page<AttendanceDailyRecordDTO>> getDailyAttendanceRecords(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) String teamName,
            @RequestParam(required = false) String employeeName,
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize) {

        try {
            Page<AttendanceDailyRecordDTO> result = attendanceService.getDailyAttendanceRecords(
                    startDate, endDate, teamName, employeeName, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取日考勤记录失败: " + e.getMessage());
        }
    }


    /**
     * 获取月度考勤汇总（按单位统计）
     * @param yearMonth 年月，格式：2025-01
     * @param teamName 单位名称（可选）
     * @param pageNum 页码
     * @param pageSize 页面大小
     * @return 分页的月度考勤汇总列表
     */
    @GetMapping("/monthly-summary-by-team")
    @ApiOperation("获取月度考勤汇总（按单位）")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Page<MonthlyAttendanceSummaryByTeamDTO>> getMonthlyAttendanceSummaryByTeam(
            @RequestParam String yearMonth,
            @RequestParam(required = false) String teamName,
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize) {

        try {
            YearMonth ym = YearMonth.parse(yearMonth);
            Page<MonthlyAttendanceSummaryByTeamDTO> result = attendanceService.getMonthlyAttendanceSummaryByTeam(ym, teamName, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取月度考勤汇总失败: " + e.getMessage());
        }
    }


    /**
     * 导出月度考勤报表
     */
    @GetMapping("/export-monthly-report")
    @ApiOperation("导出月度考勤报表")
    @PreAuthorize("hasRole('ADMIN')")
    public void exportMonthlyAttendanceReport(
            @RequestParam String yearMonth,
            @RequestParam(required = false) String teamName,
            @RequestParam(required = false) String employeeName,
            HttpServletResponse response) {

        try {
            YearMonth ym = YearMonth.parse(yearMonth);
            attendanceService.exportMonthlyAttendanceReport(ym, teamName, employeeName, response);
        } catch (Exception e) {
            throw new RuntimeException("导出月度考勤报表失败: " + e.getMessage());
        }
    }
    /**
     * 导出月度考勤汇总报表
     */
    @GetMapping("/export-monthly-summary")
    @ApiOperation("导出月度考勤汇总报表")
    @PreAuthorize("hasRole('ADMIN')")
    public void exportMonthlySummaryReport(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM") YearMonth yearMonth,
            @RequestParam(required = false) String teamName,
            @RequestParam(required = false) String employeeName,
            HttpServletResponse response) throws IOException {

        attendanceService.exportMonthlySummaryReport(yearMonth, teamName, employeeName, response);
    }

    /**
     * 新增接口：导出日考勤记录
     * GET
     *
     */
    @GetMapping("/export/daily")
    @ApiOperation("导出日考勤记录")
    @PreAuthorize("hasRole('ADMIN')")
    public void exportDailyAttendanceRecords(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) String teamName,
            @RequestParam(required = false) String employeeName,
            HttpServletResponse response) throws IOException {
        attendanceService.exportDailyAttendanceRecords(startDate, endDate, teamName, employeeName, response);
    }



}